<?
  class InputFile extends Input
  {
	var $cFilter = "";
	var $cDestinationPath = ""; // Directorio a donde se quiere dejar el archivo
	var $bClear = true;
	var $bBuscar = true;
	var $cMessage = '';
	var $nMaxLength = 40;
	var $aInvalidTypes = array('application/octet-stream');
	var $aValidTypes = array('image');

	function addValidType($cType)
	{
		$this->aValidTypes[] = $cType;
		$_SESSION['inputFile_types'] = implode(',', $this->aValidTypes);
	}
	function setMessage($cMessage)
	{
		$this->cMessage = $cMessage;
	}
	function setBuscar($bBuscar )
	{
		$this->bBuscar = $bBuscar;
	}
	function getDestinationPath( )
		{
			return $this->cDestinationPath ;
		}
	function setDestination( $cDestinationPath )
	{
		return $this->setDestinationPath( $cDestinationPath );
	}
	function setDestinationPath( $cDestinationPath )
		{
			if ( substr($cDestinationPath,-1, 1) != '/' && $cDestinationPath!= '' ) $cDestinationPath .= '/';
			$this->cDestinationPath = $cDestinationPath;
		}
	function setClear( $bClear )
		{
			$this->bClear= $bClear;
		}
  function InputFile( $cLabel, $cField, $cValue = '', $cDestinationPath = '')
	{
		$this->Input($cLabel, $cField, $cValue, false );
		$this->setDestinationPath( getParam( 'cDestinationPath' ,$cDestinationPath) );
		if ( $_SESSION['inputFile_types'] )
			$this->aValidTypes = explode( ',', $_SESSION['inputFile_types'] );
	}
	function makeUpload()
	{
		if ( $this->cValue  )
		{
			// Miestra el Nombre del Archivo
			if ( $this->cDestinationPath != '' && file_exists( $this->cDestinationPath . $this->cValue) )
			{
				/*
				$aArchivosImagenes = array( 'gif', 'jpg','jpeg', 'tif', 'tiff', 'png', 'bmp' );
				$cUrl =  '?' . PARAM_REFRESH . '=file&amp;' . PARAM_METHOD . '=getImage&amp;cDestinationPath=' . $this->cDestinationPath  . '&amp;cImage=' . $this->cValue;
				list( $cArchivo, $cExtension ) = explode( "." , $this->cValue );
				$bPreview  = in_array( strtolower($cExtension), $aArchivosImagenes) &&  substr( $this->cDestinationPath, 0, strlen(PATH_BANCO_IMAGENES ) ) == PATH_BANCO_IMAGENES ;
				if ( $bPreview )
					$cReturn .= "<img src='$cUrl'  title='" . $this->cValue . "' />&nbsp;" ;
				else
					$cReturn .= $this->cValue . " [" . filesize($this->cDestinationPath . $this->cValue) . " bytes]&nbsp;" ;
				*/
				$cReturn .= basename($this->cValue ). " [" . filesize($this->cDestinationPath . $this->cValue) . " bytes]&nbsp;" ;
				//$cReturn .=  "<a href='$cUrlVer' target='_blank' >Ver</a>&nbsp;";
			} else $cReturn .= basename($this->cValue );
		} else
		{
			$oModBase =& loadModule("base");
			$cArchivoBlank = $oModBase->getUrlImages() . 'editor/blank.htm';
			$cReturn .= "<iframe style='display:none; width: 0px; height: 0px;'  name='iframe" . $this->cField ."' src='$cArchivoBlank' ></iframe>"; 
			$cUrl =   '?' . PARAM_REFRESH . '=file&amp;' . PARAM_METHOD . '=upload&amp;cDestinationPath=' . $this->cDestinationPath  . '&amp;' . PARAM_FIELD . '=' . $this->cField;
			$cPropiedades .= " onchange=\"return sendFile( '" . $this->getFormName() . "', '$cUrl' , '" . $this->cField . "' );return false;\"";
			// Agrega el Campo Subir
			$cReturn .= "<input $cPropiedades name=\"" . $this->cField ."_file\" id=\"" . $this->cField ."_file\" type=\"file\" style=\"color: #FFFFFF; font-family: Arial; font-size: 11px; font-weight: bold;\"   accept=\"" . $this->cFilter . "\"  />";
		}
		return $cReturn;
	}
	function make()
		{
			$cReturn .= "<span id='txt" . $this->cField . "' >" ;
			$cReturn .= $this->makeUpload();
			$cReturn .= "</span>" ;

			// make del Input Hidden (lleva el nombre)
			$cReturn .= "<input type='hidden' " . $this->getEvents() . " name='" . $this->cField  . "' id='" . $this->cField  . "' value='" . $this->cValue  . "' />";
			if ( $this->bBuscar )
			{
				$cUrl =   '?' . PARAM_REFRESH . '=file&amp;' . PARAM_FIELD . '=' . $this->cField. '&amp;' . PARAM_METHOD . '=makeDirectory&amp;cFormName=' . $this->getFormName() .'&amp;cDestinationPath=' . $this->cDestinationPath ;
				$cReturn .=  "&nbsp;<input type='button'  onclick='openPopup( \"$cUrl\", \"Buscar Archivo\", 600, 500  ); return false;' value='Buscar' />&nbsp;";
			}
			$cVisibility = ( $this->cValue  ) ? 'visibility: show;': 'visibility: hidden;';
			$cUrl =   '?' . PARAM_REFRESH . '=file&amp;' . PARAM_FIELD . '=' . $this->cField. '&amp;' . PARAM_METHOD . '=makeUpload&amp;cFormName=' . $this->getFormName() .'&amp;cDestinationPath=' . $this->cDestinationPath ;
			$cReturn .=  "&nbsp;&nbsp;<input id='change" . $this->cField  . "' type='button' style='$cVisibility width: 61px; height: 20px; background-image: url(imagenes/bot_buscar.gif); border: none; color: #FFFFFF; font-family: Arial; font-size: 11px; font-weight: bold;'  onclick='send( \"$cUrl\", refreshElement, \"txt". $this->cField ."\", false ); return false;' value='Cambiar' />&nbsp;";
			if ( $this->bClear )
			{
				$cReturn .=  "<input id='delete" . $this->cField  . "'  type='button'  style='$cVisibility width: 61px; height: 20px; background-image: url(imagenes/bot_buscar.gif); border: none; color: #FFFFFF; font-family: Arial; font-size: 11px; font-weight: bold;' onclick='send( \"$cUrl\", refreshElement, \"txt". $this->cField ."\", false ); oInputHidden = document.getElementById( \"" . $this->cField ."\");oInputHidden.value = \"\";return false;' value='Borrar' />&nbsp;";
			}
			$cReturn .= "&nbsp;<span id=\"" . $this->cField ."_text\" style=\"$cVisibility font-family: Arial; font-size: 11px; font-weight: bold;\" >" . $this->cMessage. "</span>";
		  return $cReturn;
		}
	function getImage()
		{
			$cImage = getParam( "cImage" );
			if ( file_exists( $this->cDestinationPath . "$cImage"  )  )
			{
				echo join(file($this->cDestinationPath  . "$cImage"  )  );
				exit();
			}
		}
	function makeDirectory()
		{
			if ( $this->cDestinationPath )
			{
				$nFiltro = getParam( 'nFiltro', 0);
				$nOpcion = getParam( 'nOpcion', 0);
				$nqCol = 2; $nIndex = 0;
				$cDirActual = PATH_ROOT . $this->cDestinationPath;
				$cUrlBase =  '?' . PARAM_REFRESH . '=file&amp;' . PARAM_FIELD . '=' . $this->cField. '&amp;' . PARAM_METHOD . '=makeDirectory&amp;cDestinationPath=' . $this->cDestinationPath ;
				$fd = opendir( $cDirActual  );
				// Loop por cada archivo
				if ( $nOpcion == 0 )  echo "<div id='buscar_archivo'>";
				echo "<table class='list'><tr><th colspan='<?= $nqCol?>'>Ver: <a href='javascript:void(0);' onclick='send( \"$cUrlBase&amp;nFiltro=$nFiltro&amp;nOpcion=2\", refreshElement, \"buscar_archivo\", false ); return false;' >Lista</a> | <a href='javascript:void(0);' onclick='send( \"$cUrlBase&amp;nFiltro=$nFiltro&amp;nOpcion=1\", refreshElement, \"buscar_archivo\", false ); return false;' >Preview</a>
				Filtro: <a href='javascript:void(0);' onclick='send( \"$cUrlBase&amp;nOpcion=$nOpcion&amp;nFiltro=0\", refreshElement, \"buscar_archivo\", false ); return false;' >Todos</a> |<a href='javascript:void(0);' onclick='send( \"$cUrlBase&amp;nOpcion=$nOpcion&amp;nFiltro=1\", refreshElement, \"buscar_archivo\", false ); return false;' >Hoy</a></th></tr>";
				while ( $cArchivo = readdir($fd) )
				{
					$cArchivoActual = $cDirActual . "/" . $cArchivo;
					// Si es un archivo
					if ( filetype($cArchivoActual ) == 'file' )
					{
						if ( $nFiltro == 0 || date("y-m-d", filemtime($cArchivoActual)) == date("y-m-d"))
						{
							$this->cValue = $cArchivo;
							if ( ($nIndex++ % $nqCol) == 0) echo "<tr>";
							echo "<td ><a href='javascript:void(0);' onclick='";
							echo "oInputHidden = document.getElementById( \"" . $this->cField ."\");oInputHidden.value = \"$cArchivo\";closePopup(); if ( oInputHidden.getAttribute(\"onchange\") ) oInputHidden .onchange();";
							echo "oField = document.getElementById(\"txt".$this->cField."\");";
							echo "oField.innerHTML = \"";
							echo $this->makeUpload() . "\"; ";
							echo "return false;' >";
							echo ( $nOpcion == 1 ) ? "<img src='" . $this->cDestinationPath. "$cArchivo' />": $cArchivo;
							echo "</a></td>";
							if ( ($nIndex % $nqCol) == 0) echo "</tr>";
						}
					}
				}
				if ( ($nIndex % $nqCol) != 0 )
					{
						while ( ($nIndex++ % $nqCol) != 0 ) echo "<td $cWidth>&nbsp;</td>";
						echo "</tr>";
					}
				echo "</table>";
				if ( $nOpcion == 0 ) "</div>";
				closedir($fd);

			}
		}
	function validFile($cArchivoOrigen)
	{
		if(function_exists('mime_content_type'))
			$cMimeType = mime_content_type($cArchivoOrigen);
		else
			$cMimeType = system("file -bi '$cArchivoOrigen'");
		$cMimeType  = strtolower($cMimeType );
		
		// Validacion general de archivos que no se pueden subir (PHP y exes)
		list ( $cType, $cSubType ) = explode ( '/', $cMimeType );
		if ( strpos($cMimeType , 'php') > 0 ||  in_array( $cType, $this->aInvalidTypes)  ) 
		{
			addMessage("El formato es invalido ($cType) ");
			return false;
		}
		// Validacion puntual
		if (  count($this->aValidTypes) > 0 && !in_array( $cType, $this->aValidTypes)  ) 
		{
			addMessage("El formato es invalido ($cType) ");
			return false;
		}
		return true;
	}
	function getFileContent()
	{
		if ( $this->cDestinationPath )
		{
			$cArchivoOrigen = $_FILES[$this->cField . "_file"]['tmp_name'];
			return  file_get_contents( $_FILES[$this->cField . "_file"]['name']);
		}
	}
	function upload()
		{
			if ( $this->cDestinationPath )
			{
				if ( !file_exists( PATH_ROOT .$this->cDestinationPath ) ) 
				{
					mkDir(PATH_ROOT .$this->cDestinationPath  );
					chmod (PATH_ROOT .$this->cDestinationPath, 0640);
				}
				$cArchivoOrigen = $_FILES[$this->cField . "_file"]['tmp_name'];
				list( $cFileName, $cFileExtension)  = explodeFileName( $_FILES[$this->cField . "_file"]['name']);
				// Valida el Archivo antes de seguir
				if ( !$this->validFile($cArchivoOrigen) ) 
				{
					echo "<script>alert('El formato es invalido');</script>";
					return false;
				}
				
				if ( strlen($cFileName) + strlen($cFileExtension) >= $this->nMaxLength ) $cFileName = substr($cFileName, 0, $this->nMaxLength - strlen($cFileExtension) - 1);
				$cArchivoUpload = $this->cDestinationPath . $cFileName . '.' . $cFileExtension ;
				//$cArchivoUpload = $this->cDestinationPath . $_FILES[$this->cField . "_file"]['tmp_name'] ;
				$bError = false;
				if( $cArchivoOrigen )
				{
					$bError = copy($cArchivoOrigen , $cArchivoUpload );
					chmod ($cArchivoUpload , 0664);
					$this->cValue = $cArchivoUpload;
					echo "<script>
							oField = parent.document.getElementById('txt".$this->cField."');
							oInput = parent.document.getElementById('change".$this->cField."');
							if ( oInput ) oInput.style.visibility ='visible';
							oInput = parent.document.getElementById('delete".$this->cField."');
							if ( oInput ) oInput.style.visibility ='visible';
							oInputHidden = parent.document.getElementById('".$this->cField."');
							oInputHidden.value = '" . $cFileName . '.' . $cFileExtension . "';
							if ( oInputHidden.getAttribute('onchange') )
							{
								oInputHidden.onchange();
							}							
							oField.innerHTML = \"";
					echo $this->makeUpload();
					echo "\";</script>";
				}
			}
			// Si no hubo Error devuelve el nombre del archivo donde lo subio
			return ( $bError ) ? $cArchivoUpload : '';
		}
	}
?>